package com.mondo.financialwallet.presentation.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.widget.Button;
import android.widget.TextView;

import com.example.common.ui.AbsNetworkStateActivity;
import com.example.common.widget.state.NetworkStateLayout;
import com.github.mikephil.charting.charts.LineChart;
import com.mondo.financialwallet.R;
import com.mondo.financialwallet.data.DataRepository;
import com.mondo.financialwallet.data.entity.HoldProductDetailsEntity;
import com.mondo.financialwallet.data.entity.SingleHoldProductProfitDataEntity;
import com.mondo.financialwallet.presentation.model.HoldProduct;
import com.mondo.financialwallet.presentation.model.ProductProfitDataModel;
import com.mondo.financialwallet.presentation.ui.dialog.TipsDialog;
import com.mondo.financialwallet.presentation.utils.ActivityTitleBarHelper;
import com.mondo.financialwallet.presentation.utils.AndroidUtils;
import com.mondo.financialwallet.presentation.utils.LineChartUtils;
import com.mondo.financialwallet.presentation.ui.widget.ProductLifecycleView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.Bind;

/**
 * 持有产品详情
 */
public class HoldProductDetailsActivity extends AbsNetworkStateActivity {

    private static final String EXTRA_PRODUCT = "PRODUCT";

    public static void launch(Context context, HoldProduct product) {
        context.startActivity(new Intent(context, HoldProductDetailsActivity.class)
                .putExtra(EXTRA_PRODUCT, product));
    }

    @Bind(R.id.current_income_text_view) TextView mCurrentIncomeTextView;
    @Bind(R.id.product_total_amount_text) TextView mProductTotalAmountText;
    @Bind(R.id.yesterday_earnings_text) TextView mYesterdayEarningsText;
    @Bind(R.id.remaining_period_text) TextView mRemainingPeriodText;
    @Bind(R.id.investment_amount_text) TextView mInvestmentAmountText;
    @Bind(R.id.publish_company_text) TextView mPublishCompanyText;
    @Bind(R.id.fund_direction_text) TextView mFundDirectionText;
    @Bind(R.id.investment_strategy_text) TextView mInvestmentStrategyText;
    @Bind(R.id.liquidation_tips_text) TextView mLiquidationTipsText;
    @Bind(R.id.product_lifecycle_view) ProductLifecycleView mLifecycleView;
    @Bind(R.id.product_income_line_chart) LineChart mProductIncomeLineChart;
    @Bind(R.id.button_liquidation) Button mLiquidationView;
    @Bind(R.id.product_income_state_layout) NetworkStateLayout mProductIncomeStateLayout;

    private int mProductType;
    private HoldProduct mProduct;

    @Override
    public int getTitleLayoutRes() {
        return R.layout.include_default_title_bar;
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_hold_product_details;
    }

    @Override
    protected void initActions() {
        // 持有产品
        mProduct = (HoldProduct) getIntent().getSerializableExtra(EXTRA_PRODUCT);

        // 标题
        ActivityTitleBarHelper.init(this, mProduct.getName());

        // 清算
        mLiquidationView.setOnClickListener(v -> liquidationProduct());

        // 初始化图表
        requestHoldProductProfitData();

        // 请求持有产品详情
        requestHoldProductDetails();
    }

    private void liquidationProduct() {
        // 0 活期 1 定期
        int message = mProductType == 0
                ? R.string.dialog_message_liquidation_current_tips
                : R.string.dialog_message_liquidation_regular_tips;

        TipsDialog.warning(this).build(
                R.string.dialog_title_warning_tips,
                message,
                b -> ProductLiquidationActivity.launch(this, mProduct))
                .show();
    }

    private void requestHoldProductProfitData() {
        mProductIncomeStateLayout.loadingNetwork();

        DataRepository.get().singleHoldProductProfitData(mProduct.getOrderNumber(), result -> {
            if (result == null) {
                mProductIncomeStateLayout.emptyNetwork();
                return;
            }

            if (result.isSuccess()) {
                List<SingleHoldProductProfitDataEntity.DataBean> data = result.getData();
                List<ProductProfitDataModel> list = new ArrayList<>();
                if (data != null && data.size() > 0) {
                    mProductIncomeStateLayout.successNetwork();
                    for (SingleHoldProductProfitDataEntity.DataBean dataBean : data) {
                        list.add(new ProductProfitDataModel(dataBean.getProfit(), dataBean.getDate()));
                    }

                } else {
                    mProductIncomeStateLayout.emptyNetwork();
                }

                // 收益图表
                LineChartUtils.init(getString(R.string.label_daily_income), mProductIncomeLineChart, list);
            } else {

                mProductIncomeStateLayout.emptyNetwork();
            }
        });
    }

    private void requestHoldProductDetails() {
        loadingNetwork();

        DataRepository.get().holdProductDetails(mProduct.getOrderNumber(), result -> {
            if (result.isSuccess()) {
                successNetwork();
                HoldProductDetailsEntity.DataBean data = result.getData();

                // 产品类型
                mProductType = data.getGoods_type();

                // 产品描述
                mCurrentIncomeTextView.setText(data.getGoods_profit()); // 当前收益
                mProductTotalAmountText.setText(data.getGoods_price()); // 产品总额
                mYesterdayEarningsText.setText(data.getYesterday_profit()); // 昨日收益
                mRemainingPeriodText.setText(mProduct.getMinimumDay()); // 剩余期限

                // 生命周期
                mLifecycleView.setData(Arrays.asList(
                        new ProductLifecycleView.Data(getString(R.string.purchase_date), data.getPay_at()),
                        new ProductLifecycleView.Data(getString(R.string.increase_interest_date), data.getInterest_at()),
                        new ProductLifecycleView.Data(getString(R.string.expiry_date), data.getExpire_at()),
                        new ProductLifecycleView.Data(getString(R.string.return_date), data.getRedeem_at())
                ));

                // 产品详情
                mInvestmentAmountText.setText("$" + data.getGoods_price()); // 产品价格
                mPublishCompanyText.setText(data.getCompany_name()); // 公司名称
                mFundDirectionText.setText(data.getFund_invest()); // 资金投向
                mInvestmentStrategyText.setText(data.getInvestment_strategy()); // 投资策略
                mLiquidationTipsText.setText(Html.fromHtml(
                        String.format(getString(R.string.text_hold_product_tips_details), data.getClose_day())
                ));

                // 是否可清算
                AndroidUtils.toggleLiquidationButtonState(mLiquidationView, data.isIs_period());
            } else {
                errorNetwork(result.getMsg());
            }
        });
    }

    @Override
    public void onAnewRequest() {
        requestHoldProductDetails();
    }
}
